﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Dcms.BLL;
using Dcms.Model;
using Dcms.Common;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;

public partial class Manage_Modle_ModelField_CreateModelField : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DealXmlModel();
        CreateModelField();
    }

    #region 将模块写入到模块表中
    private void DealXmlModel()
    {
        string strXmlPath = Server.MapPath("~/Dcw_WebModelFile.xml");
        XmlDocument objXmlDoc = new XmlDocument();
        objXmlDoc.Load(strXmlPath);
        XmlNodeList xmlNodeList = objXmlDoc.SelectNodes("root/node");
        Dcms_ModelBLL bllDcms_ModelBLL = new Dcms_ModelBLL();
        foreach (XmlNode xmlNode in xmlNodeList)
        {
            XmlElement xe = (XmlElement)xmlNode;
            string strModelName = xe.GetAttribute("typeName");
            string strModelType = xe.GetAttribute("Type");
            int intOrder = bllDcms_ModelBLL.CheckModel(strModelName, strModelType, "cn");
            if (intOrder == -1)
            {
                Dcms_ModelModel etDcms_ModelModel = new Dcms_ModelModel();
                etDcms_ModelModel.Model_Intro = "";
                etDcms_ModelModel.Model_Lang = "cn";
                etDcms_ModelModel.Model_Level = 0;
                etDcms_ModelModel.Model_Name = strModelName;
                etDcms_ModelModel.Model_Type = strModelType;
                bllDcms_ModelBLL.AddModel(etDcms_ModelModel);
            }
        }
    }
    #endregion

    #region 生成

    /// <summary>
    /// 生成
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void CreateModelField()
    {
        CreateForm();
    }

    /// <summary>
    /// 生成表单
    /// </summary>
    private void CreateForm()
    {
        string strXmlPath = Server.MapPath("~/Dcw_WebModelFile.xml");
        //1。从模块表中取得所有内容
        Dcms_ModelBLL bllDcms_ModelBLL = new Dcms_ModelBLL();
        IList<Dcms_ModelModel> lDcms_ModelModel = bllDcms_ModelBLL.GetModelList("");
        foreach (Dcms_ModelModel etDcms_ModelModel in lDcms_ModelModel)
        { 
            //2。取得xml中的模块字段配置
            XmlDocument objXmlDoc = new XmlDocument();
            objXmlDoc.Load(strXmlPath);
            XmlNodeList xmlNodeList = objXmlDoc.SelectNodes("root/node");
            string strControls = "";
            string strBackground = "#FAFAFA";
            foreach(XmlNode xmlNode in xmlNodeList)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("typeName", typeof(string)));
                dt.Columns.Add(new DataColumn("DefaultValue", typeof(string)));
                dt.Columns.Add(new DataColumn("HelpInfo", typeof(string)));
                dt.Columns.Add(new DataColumn("IsCheck", typeof(string)));
                dt.Columns.Add(new DataColumn("IsHide", typeof(string)));
                dt.Columns.Add(new DataColumn("Label", typeof(string)));
                dt.Columns.Add(new DataColumn("Label1", typeof(string)));
                dt.Columns.Add(new DataColumn("MustField", typeof(string)));
                dt.Columns.Add(new DataColumn("Name", typeof(string)));
                dt.Columns.Add(new DataColumn("Order", typeof(string)));
                dt.Columns.Add(new DataColumn("Reg", typeof(string)));
                dt.Columns.Add(new DataColumn("RegMsg", typeof(string)));
                dt.Columns.Add(new DataColumn("RequiredField", typeof(string)));
                dt.Columns.Add(new DataColumn("Type", typeof(string)));
                dt.Columns.Add(new DataColumn("WebId", typeof(string)));
                dt.Columns.Add(new DataColumn("FileconControl", typeof(string)));
                dt.Columns.Add(new DataColumn("rbl", typeof(string)));
                dt.Columns.Add(new DataColumn("FieldInfo", typeof(string)));

                XmlElement xe = (XmlElement)xmlNode;
                if (xe.GetAttribute("typeName") == etDcms_ModelModel.Model_Name && xe.GetAttribute("Type").ToLower() == etDcms_ModelModel.Model_Type.ToLower())
                {
                    //找到对应的字段并写入到临时表中
                    string strFieldInfo = xmlNode.InnerText;
                    if (strFieldInfo != "" && xe.GetAttribute("IsHide") == "1")
                    {
                        DataRow dr = dt.NewRow();
                        dr["typeName"] = xe.GetAttribute("typeName");
                        dr["DefaultValue"] = xe.GetAttribute("DefaultValue");
                        dr["HelpInfo"] = xe.GetAttribute("HelpInfo");
                        dr["IsCheck"] = xe.GetAttribute("IsCheck");
                        dr["IsHide"] = xe.GetAttribute("IsHide");
                        dr["Label"] = xe.GetAttribute("Label");
                        dr["Label1"] = xe.GetAttribute("Label1");
                        dr["MustField"] = xe.GetAttribute("MustField");
                        dr["Name"] = xe.GetAttribute("Name");
                        dr["Order"] = xe.GetAttribute("Order");
                        dr["Reg"] = xe.GetAttribute("Reg");
                        dr["RegMsg"] = xe.GetAttribute("RegMsg");
                        dr["RequiredField"] = xe.GetAttribute("RequiredField");
                        dr["Type"] = xe.GetAttribute("Type");
                        dr["WebId"] = xe.GetAttribute("WebId");
                        dr["FileconControl"] = xe.GetAttribute("FileconControl");
                        dr["rbl"] = xe.GetAttribute("rbl");
                        dr["FieldInfo"] = strFieldInfo;
                        dt.Rows.Add(dr);
                    }
                }
                if (dt.Rows.Count > 0)
                {
                    //有内容

                    DataView dv = dt.DefaultView;
                    dv.Sort = "Order";

                    foreach (DataRowView drv in dv)
                    {
                        string strFieldInfo = drv["FieldInfo"].ToString();
                        //取得帮助提示,当无帮助时不显示
                        string strHelp = "";
                        if (drv["HelpInfo"].ToString() != "")
                        {
                            strHelp = "<img src=\"../../images/icon3.gif\" onmouseover='divShow(\"" + drv["HelpInfo"].ToString() + "\")' onmouseout=\"divHide()\" />";
                        }

                        //{0}-->背景色   {1}-->显示标签  {2}-->字段帮助  {3}-->正则  {4}-->错误信息
                        if (drv["Reg"].ToString() != "" && drv["MustField"].ToString() == "1")
                        {
                            strControls += string.Format(strFieldInfo, strBackground, drv["Label1"].ToString(), strHelp, drv["Reg"].ToString(), drv["RegMsg"].ToString());
                        }
                        else
                        {
                            if (drv["RequiredField"].ToString() == "0")
                            {
                                //过滤必填
                                Regex regex = new Regex(@"<asp:RequiredFieldValidator [^>]*>[\s]*</asp:RequiredFieldValidator>");
                                strFieldInfo = regex.Replace(strFieldInfo, "");
                            }
                            if (drv["Reg"].ToString() == "")
                            {
                                //过滤验证
                                Regex regex = new Regex(@"<asp:RegularExpressionValidator [^>]*>[\s]*</asp:RegularExpressionValidator>");
                                strFieldInfo = regex.Replace(strFieldInfo, "");
                            }
                            strControls += string.Format(strFieldInfo, strBackground, drv["Label1"].ToString(), strHelp, drv["Reg"].ToString(), drv["RegMsg"].ToString());
                        }
                        strBackground = strBackground == "#FAFAFA" ? "#F2F2F2" : "#FAFAFA";
                    }
                }
            }
            if (strControls != "")
            {
                #region 3。取得模板路径及保存路径
                string strEditTemplatePath = "";
                string strEditDestPath = "";
                string strListTemplatePath = "";
                string strListDestPath = "";

                if (GetTemplatePath(etDcms_ModelModel.Model_Type, out strEditTemplatePath, out strEditDestPath, out strListTemplatePath, out strListDestPath) == false)
                {
                    //出错
                    RegisterStartupScript(this.ToString(), "<script language='javascript'>alert('取模板路径时出错，请联系管理员！');</script>");
                    return;
                }
                #endregion

                #region 4。取得模板
                string strFileContent = GetTemplate(strEditTemplatePath);
                #endregion

                #region 5。替换相关标签
                strFileContent = strFileContent.Replace("{Controls}", strControls);
                #endregion

                #region 6。保存文件
                //保存编辑页面
                strEditDestPath = string.Format(strEditDestPath, etDcms_ModelModel.Model_Order);
                SaveFile(strEditDestPath, strFileContent);

                //保存列表页面
                strFileContent = GetTemplate(strListTemplatePath);
                strFileContent = strFileContent.Replace("{ModelKeyID}", etDcms_ModelModel.Model_Order.ToString());
                strListDestPath = string.Format(strListDestPath, etDcms_ModelModel.Model_Order);
                SaveFile(strListDestPath, strFileContent);

                //设置为已使用
                etDcms_ModelModel.Model_UseFlag = 1;
                bllDcms_ModelBLL.Update(etDcms_ModelModel);

                #endregion
            }
            else
            { 
                //没有字段配置
                //判断是否为基础模块
                if (etDcms_ModelModel.Model_Order != 0 && etDcms_ModelModel.Model_Type.ToLower() != "catesystem" && etDcms_ModelModel.Model_Type.ToLower() != "websiteinfo" && etDcms_ModelModel.Model_Type.ToLower() != "system")
                {
                    //不是基础模块,删除
                    bllDcms_ModelBLL.DeleteModelByID(etDcms_ModelModel.Model_ID);
                }
                else
                { 
                    //是基础模块,则设置为未使用
                    etDcms_ModelModel.Model_UseFlag = 0;
                    bllDcms_ModelBLL.Update(etDcms_ModelModel);
                }
            }
        }
        RegisterStartupScript(this.ToString(), "<script language='javascript'>alert('生成完成！');</script>");
    }

    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="strFileName"></param>
    /// <param name="strFileContent"></param>
    /// <returns></returns>
    private void SaveFile(string strFileName, string strFileContent)
    {
        using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            try
            {
                Byte[] info = System.Text.Encoding.UTF8.GetBytes(strFileContent);
                fs.Write(info, 0, info.Length);
                fs.Close();
            }
            catch (Exception ex)
            {
            }
        }
    }

    /// <summary>
    /// 取得模板路径及保存对应的路径
    /// </summary>
    /// <param name="strModelName">模块名称</param>
    /// <param name="strEditTemplatePath">编辑模板</param>
    /// <param name="strEditDestPath">编辑页面保存路径</param>
    /// <param name="strListTemplatePath">列表模板</param>
    /// <param name="strListDestPath">列表页面保存路径</param>
    /// <returns></returns>
    private bool GetTemplatePath(string strModelName, out string strEditTemplatePath, out string strEditDestPath, out string strListTemplatePath, out string strListDestPath)
    {
        bool blnRef = false;
        strEditTemplatePath = "";
        strEditDestPath = "";
        strListTemplatePath = "";
        strListDestPath = "";
        try
        {
            string strXmlPath = Server.MapPath(@"~\Manage\Modle\ModelField\FilePath.xml");
            DataSet ds = DcmsXmlHelper.GetXmlData(strXmlPath, "root");
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    if (string.Compare(dr["name"].ToString(), strModelName, true) == 0)
                    {
                        switch (dr["PageType"].ToString().ToLower())
                        {
                            case "edit":
                                strEditTemplatePath = Server.MapPath(dr["TemplatePath"].ToString());
                                strEditDestPath = Server.MapPath(dr["DestPath"].ToString());
                                break;
                            case "list":
                                strListTemplatePath = Server.MapPath(dr["TemplatePath"].ToString());
                                strListDestPath = Server.MapPath(dr["DestPath"].ToString());
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            blnRef = true;
        }
        catch
        {
        }
        return blnRef;
    }

    /// <summary>
    /// 取得模板内容
    /// </summary>
    private string GetTemplate(string strFilePath)
    {
        string strTemplateText = "";

        //如果指定风格的模板文件不存在...
        if (System.IO.File.Exists(strFilePath))
        {
            using (System.IO.StreamReader objReader = new System.IO.StreamReader(strFilePath, Encoding.UTF8))
            {
                //读取开始
                StringBuilder textOutput = new StringBuilder();
                textOutput.Append(objReader.ReadToEnd());
                objReader.Close();
                strTemplateText = textOutput.ToString();
            }
        }
        return strTemplateText;
    }
    #endregion
}
